"""
自动更新群名片插件
功能：自动匹配数据库中的QQ号，并将对应的群名片更新为数据库中的信息

现在使用 Django Model 来管理数据库操作
"""
from typing import Dict, List

from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageSegment
from nonebot.exception import FinishedException

# 使用 Django Model 替代直接 SQL 操作
from src.common.django_db import get_user_nicknames_by_qq_numbers

# 创建命令处理器
auto_update_nickname = on_command("自动更新群名片", priority=5)


async def batch_get_user_nicknames(qq_numbers: List[int]) -> Dict[int, str]:
    """
    批量获取多个QQ号的群名片信息（插件内部函数）
    
    现在使用 Django Model 来查询，更简洁和安全
    
    Args:
        qq_numbers: QQ号列表
        
    Returns:
        Dict[qq_number, nickname] 格式的字典，只包含数据库中存在的QQ号
    """
    if not qq_numbers:
        return {}
    
    # 使用 Django Model 批量查询
    return await get_user_nicknames_by_qq_numbers(qq_numbers)


@auto_update_nickname.handle()
async def handle_auto_update_nickname(bot: Bot, event: GroupMessageEvent):
    """自动匹配数据库并更新群名片"""
    print(f"[DEBUG] 收到自动更新群名片命令，群号: {event.group_id}, 用户: {event.user_id}")
    
    try:
        group_id = event.group_id
        
        # 获取群成员列表（尝试强制刷新缓存）
        try:
            # 尝试使用 no_cache 参数强制刷新
            member_list = await bot.get_group_member_list(group_id=group_id, no_cache=True)
        except TypeError:
            # 如果不支持 no_cache 参数，使用默认方式
            member_list = await bot.get_group_member_list(group_id=group_id)
        
        if not member_list:
            await auto_update_nickname.finish("无法获取群成员列表")
            return
        
        # 提取所有群成员的QQ号
        group_member_qqs = [member['user_id'] for member in member_list]
        print(f"[DEBUG] 群成员总数: {len(group_member_qqs)}")
        
        # 批量查询数据库中存在的QQ号和对应的群名片
        db_nickname_map = await batch_get_user_nicknames(group_member_qqs)
        print(f"[DEBUG] 数据库中匹配到的QQ号: {len(db_nickname_map)}")
        
        if not db_nickname_map:
            await auto_update_nickname.finish("数据库中没有找到匹配的QQ号")
            return
        
        # 统计信息
        success_count = 0
        fail_count = 0
        skip_count = 0
        update_details = []
        
        # 遍历匹配到的用户，更新群名片
        for qq_number, target_nickname in db_nickname_map.items():
            # 获取当前群成员的群名片
            member_info = next((m for m in member_list if m['user_id'] == qq_number), None)
            if not member_info:
                print(f"[WARN] 未找到成员 {qq_number} 的信息")
                continue
            
            current_card = member_info.get('card', '') or member_info.get('nickname', '')
            print(f"[DEBUG] 成员 {qq_number}: 当前群名片='{current_card}', 目标='{target_nickname}'")
            
            # 如果当前群名片已经是目标群名片，则跳过
            if current_card == target_nickname:
                skip_count += 1
                print(f"[DEBUG] 跳过 {qq_number}: 群名片已是最新")
                continue
            
            try:
                print(f"[DEBUG] 开始更新 {qq_number}: {current_card} → {target_nickname}")
                # 调用API修改群名片
                await bot.set_group_card(
                    group_id=group_id,
                    user_id=qq_number,
                    card=target_nickname
                )
                
                success_count += 1
                update_details.append(f"{qq_number}: {current_card} → {target_nickname}")
                print(f"[INFO] 成功更新 {qq_number} 的群名片: {current_card} → {target_nickname}")
            except Exception as e:
                fail_count += 1
                print(f"[ERROR] 更新 {qq_number} 的群名片失败: {str(e)}")
                update_details.append(f"{qq_number}: 更新失败 - {str(e)}")
        
        
        # 验证更新结果（重新获取群成员列表）
        verification_results = []
        if success_count > 0:
            print(f"[DEBUG] 验证更新结果...")
            try:
                # 重新获取群成员列表验证
                verify_member_list = await bot.get_group_member_list(group_id=group_id)
                for qq_number, target_nickname in db_nickname_map.items():
                    verify_member = next((m for m in verify_member_list if m['user_id'] == qq_number), None)
                    if verify_member:
                        actual_card = verify_member.get('card', '') or verify_member.get('nickname', '')
                        is_correct = (actual_card == target_nickname)
                        verification_results.append((qq_number, actual_card, target_nickname, is_correct))
                        print(f"[DEBUG] 验证 {qq_number}: 实际='{actual_card}', 目标='{target_nickname}', 正确={is_correct}")
            except Exception as e:
                print(f"[WARN] 验证更新结果失败: {e}")
        
        # 生成结果消息
        message_parts = []
        message_parts.append(MessageSegment.text(f"📋 自动更新群名片结果\n\n"))
        message_parts.append(MessageSegment.text(f"✅ 成功更新: {success_count} 人\n"))
        message_parts.append(MessageSegment.text(f"⏭️  跳过（已是最新）: {skip_count} 人\n"))
        message_parts.append(MessageSegment.text(f"❌ 更新失败: {fail_count} 人\n"))
        message_parts.append(MessageSegment.text(f"📊 数据库中匹配: {len(db_nickname_map)} 人\n\n"))
        
        # 添加验证结果
        if verification_results:
            correct_count = sum(1 for _, _, _, is_correct in verification_results if is_correct)
            message_parts.append(MessageSegment.text(f"🔍 验证结果: {correct_count}/{len(verification_results)} 人已正确更新\n\n"))
        
        if update_details:
            message_parts.append(MessageSegment.text("详细更新记录：\n"))
            for detail in update_details[:10]:  # 最多显示10条
                message_parts.append(MessageSegment.text(f"{detail}\n"))
            if len(update_details) > 10:
                message_parts.append(MessageSegment.text(f"... 还有 {len(update_details) - 10} 条记录\n"))
        
        await auto_update_nickname.finish(message_parts)
        
    except FinishedException:
        raise
    except Exception as e:
        print(f"[ERROR] 自动更新群名片时发生错误: {str(e)}")
        import traceback
        traceback.print_exc()
        await auto_update_nickname.finish(f"自动更新群名片时发生错误: {str(e)}")

